﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Xml;
using eBdb.EpubReader;
using mshtml;
using System.IO;
//using CapstoneProjectAEReader.Common.Utility;
using System.Runtime.InteropServices;
using System.Windows.Media;
using CapstoneProjectAEReader.Entities.Models;
using System.Text.RegularExpressions;

namespace CapstoneProjectAEReader.Business.E_book_Reader
{
    public partial class epubReaderControl : IBook
    {
        private HTMLDocument HTMLDoc;
        private IHTMLElementCollection HrElementCollection;
        private IHTMLElement getLastPage;
        private int getTotalPage = 0;
        private string currentPage = "0";
        private string getFileLocation;
        private string progress = "Loading";
        int zoomFactor = 0;
        public XmlDocument xDoc;
        public string xmlFilePath;
        private IHTMLDocument2 IHMLDoc2;
        private IHTMLStyleSheetsCollection getStyleSheet;
        private System.Windows.Forms.HtmlDocument originalDoc;
        private bool loadOnce = false;
        private string _contentBeforeHighLight;

        public override void LoadFile(string strFileName)
        {
            //InitializeComponent();
            getFileLocation = strFileName;
            startEPUBLoading();
        }

        public epubReaderControl(int mode)
        {
            InitializeComponent();
        }

        #region Modify InnerHtml
        public override void HightLightWord(string getWord)
        {
            var doc = epubReader.Document;
            StringBuilder html = new StringBuilder(_contentBeforeHighLight);
            
            getWord.Trim();
            //var words = new[] { "Reki", "google", "Although I retorted sarcastically, my eyes couldn’t help but weep." };
            if (getWord != "" && getWord != null)
            {
                String[] words = new[] { getWord };

                foreach (String key in words)
                {
                    String substitution = "<span style='background-color: rgb(60, 230, 76);'>" + key + "</span>";
                    html.Replace(key, substitution);
                }
            }
            doc.Body.InnerHtml = html.ToString();
        }

        public override void SetReadingMode(int mode)
        {
            string color;
            string background;
            if(mode == 0)
            {
                color = "black";
                background = "white";
            }
            else
            {
                color = "white";
                background = "black";
            }
            HTMLDoc.body.style.color = color;
            HTMLDoc.body.style.background = background;
            if (getStyleSheet.item(0) != null)
            {
                IHTMLStyleSheet getStyle = getStyleSheet.item(0);
                if(getStyle.rules.length > 0 && getStyle.rules.item(0) !=null)
                {
                    getStyle.removeRule(0);
                }
                getStyle.addRule("p", String.Format("color:{0} !important",color),0);
            }
        }

        public override void SetFontSize(int size)
        {
            if (size > 0)
            {
                HTMLDoc.body.style.fontSize = size;
                if (getStyleSheet.item(0) != null)
                {
                    IHTMLStyleSheet getStyle = getStyleSheet.item(0);
                    if (getStyle.rules.length > 0 && getStyle.rules.item(1) != null)
                    {
                        getStyle.removeRule(1);
                    }
                    getStyle.addRule("p", String.Format("font-size:{0}pt !important", size),1);
                }
            }
            else
            {

                epubReader.DocumentText = _contentBeforeHighLight;
            }
        }

        public override void SetFontType(string type)
        {
            if (!String.IsNullOrEmpty(type))
            {
                HTMLDoc.body.style.fontFamily = type;
                if (getStyleSheet.item(0) != null)
                {
                    IHTMLStyleSheet getStyle = getStyleSheet.item(0);
                    if (getStyle.rules.length > 0 && getStyle.rules.item(2) != null)
                    {
                        getStyle.removeRule(2);
                    }
                    getStyle.addRule("p", String.Format("font-family:{0} !important;", type),2);
                }
            }
            else
            {
                epubReader.DocumentText = _contentBeforeHighLight;
            }
        }
        #endregion

        #region Loading
        private void epubReader_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HTMLDoc = (HTMLDocument)epubReader.Document.DomDocument;
            HrElementCollection = HTMLDoc.getElementsByTagName("hr");
            //Get Style Sheet
            IHMLDoc2 = (IHTMLDocument2)epubReader.Document.DomDocument;
            getStyleSheet = IHMLDoc2.styleSheets;
            //Get Original Doc

            zoomFactor = 100;
            progress = "Done";
            epubReader.Focus();
        }

        private void DoLoading(object sender, DoWorkEventArgs e)
        {
            Epub epub = new Epub(getFileLocation);
            string documentText = null;
            documentText = epub.GetContentAsHtml();
            epubReader.DocumentText = documentText;
            _contentBeforeHighLight = documentText;
            getLastPage = null;
            getTotalPage = epub.epubPage;

            // -- Do WTF -- ?
            string xmlFileName;
            string strTempFolder;
            string booktitle = "Unknown";
            booktitle = Path.GetFileNameWithoutExtension(getFileLocation);
            //if (epub.Title[0] != null)
            //{
            //    booktitle = epub.Title[0];
            //}
            xmlFileName = booktitle + ".xml";
            strTempFolder = "AeReaderData\\Temp";
            if (!Directory.Exists(strTempFolder))
            {
                Directory.CreateDirectory(strTempFolder);
            }
            //Create xml bookmark
            xmlFilePath = strTempFolder + "\\" + xmlFileName;
            if (!File.Exists(xmlFilePath))
            {
                //System.IO.File.WriteAllText(@xmlFilePath, "WTF?");
                ExportBookmarksToXml(getFileLocation, xmlFilePath, "");
            }
            //Create Cover
            string imageFilePath = strTempFolder + "\\" + booktitle + ".png";
            if (!File.Exists(imageFilePath))
            {
                GetPdfThumbnail(getFileLocation, imageFilePath);
            }
        }

        public override string CheckLoading()
        {
            return progress;
        }

        public void startEPUBLoading()
        {
            //create background worker
            BackgroundWorker worker = new BackgroundWorker();
            //end work
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompleteLoading);
            //assign it work
            worker.DoWork += new DoWorkEventHandler(DoLoading);
            //start work
            worker.RunWorkerAsync();
        }

        void CompleteLoading(object sender, RunWorkerCompletedEventArgs e)
        {
            BackgroundWorker finishWorker = sender as BackgroundWorker;
            finishWorker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(CompleteLoading);
            finishWorker.DoWork -= new DoWorkEventHandler(DoLoading);
            //MessageBox.Show("Done");
        }
        #endregion

        #region Control
        public override string CheckCurrentPage()
        {
            if (HrElementCollection != null)
            {
                int getCurrent_OffsetY = HTMLDoc.documentElement.getAttribute("scrollTop");
                int getCompare_OffsetY = 0;
                int compareResult = 0;
                int currentResult = int.MaxValue;
                foreach (IHTMLElement curElement in HrElementCollection)
                {
                    getCompare_OffsetY = curElement.offsetTop;
                    compareResult = getCurrent_OffsetY - getCompare_OffsetY;
                    if (compareResult >= 0 && compareResult <= currentResult)
                    {
                        currentResult = compareResult;
                        currentPage = curElement.id;
                        currentPage = currentPage.Substring(8);
                    }
                }
                return currentPage;
            }
            else
            {
                return "NaN";
            }
        }

        public override void DisplayNextPage()
        {
            int getNextPage = int.Parse(currentPage);
            if (HrElementCollection != null && getNextPage < getTotalPage)
            {
                getNextPage += 1;
                currentPage = getNextPage.ToString();
                string pageID = "headpage" + currentPage;
                IHTMLElement curElement = HTMLDoc.getElementById(pageID);
                if (curElement != null)
                {
                    int offSetTop = curElement.offsetTop + 10;
                    HTMLDoc.parentWindow.scrollTo(0, offSetTop);
                }
            }
        }

        /// <summary>
        /// Display previous page
        /// </summary>
        public override void DisplayPrevioudPage()
        {
            int getNextPage = int.Parse(currentPage);
            if (HrElementCollection != null && getNextPage >= 1)
            {
                getNextPage -= 1;
                currentPage = getNextPage.ToString();
                string pageID = "headpage" + currentPage;
                IHTMLElement curElement = HTMLDoc.getElementById(pageID);
                if (curElement != null)
                {
                    int offSetTop = curElement.offsetTop + 10;
                    HTMLDoc.parentWindow.scrollTo(0, offSetTop);
                }
            }
        }

        /// <summary>
        /// Display first page
        /// </summary>
        public override void DisplayFirstPage()
        {
            if (HrElementCollection != null)
            {
                foreach (IHTMLElement curElement in HrElementCollection)
                {
                    string getPageID = curElement.getAttribute("id");
                    if (getPageID == "headpage1")
                    {
                        int offSetTop = curElement.offsetTop + 10;
                        HTMLDoc.parentWindow.scrollTo(0, offSetTop);
                        currentPage = "0";
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Display last page
        /// </summary>
        public override void DisplayLastPage()
        {
            if (getLastPage == null)
            {
                string lastPageString = "headpage" + getTotalPage;
                foreach (IHTMLElement curElement in HrElementCollection)
                {
                    string getPageID = curElement.getAttribute("id");
                    if (getPageID == lastPageString)
                    {
                        getLastPage = curElement;
                        int offSetTop = getLastPage.offsetTop + 10;
                        HTMLDoc.parentWindow.scrollTo(0, offSetTop);
                        currentPage = getTotalPage.ToString();
                        break;
                    }
                }
            }
            else
            {
                int offSetTop = getLastPage.offsetTop + 10;
                HTMLDoc.parentWindow.scrollTo(0, offSetTop);
                currentPage = getTotalPage.ToString();
            }
        }

        /// <summary>
        /// Zoom in
        /// </summary>
        public override void ZoomIn()
        {
            if (zoomFactor <= 280)
            {
                zoomFactor += 20;
                ((SHDocVw.WebBrowser)epubReader.ActiveXInstance).ExecWB(SHDocVw.OLECMDID.OLECMDID_OPTICAL_ZOOM,
                SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, zoomFactor, IntPtr.Zero);
            }
            else
            {
                System.Windows.MessageBox.Show("Maximum Zoom Out!!!");
            }

        }

        /// <summary>
        /// Zoom out
        /// </summary>
        public override void ZoomOut()
        {
            if (zoomFactor >= 20)
            {
                zoomFactor -= 20;
                ((SHDocVw.WebBrowser)epubReader.ActiveXInstance).ExecWB(SHDocVw.OLECMDID.OLECMDID_OPTICAL_ZOOM,
                SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, zoomFactor, IntPtr.Zero);
            }
            else
            {
                System.Windows.MessageBox.Show("Minimum Zoom Out !!!");
            }
        }

        /// <summary>
        /// Go to specific page
        /// </summary>
        /// <param name="pageNumber">Desired Page Number</param>
        public override void GoToPage(int pageNumber)
        {
            try
            {
                int getPage = pageNumber;
                if (HrElementCollection != null && getPage >= 0 && getPage <= getTotalPage)
                {
                    currentPage = getPage.ToString();
                    string pageID = "headpage" + currentPage;
                    IHTMLElement curElement = HTMLDoc.getElementById(pageID);
                    if (curElement != null)
                    {
                        int offSetTop = curElement.offsetTop + 10;
                        HTMLDoc.parentWindow.scrollTo(0, offSetTop);
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show("Page doesn't exist !!!");
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Please input positive integer !!!");
            }
        }

        /// <summary>
        /// Open Note Form
        /// </summary>
        /// <param name="selectedContent">selected content</param>
        public override string GetSelectedText()
        {
            string getText = null;
            IHTMLDocument2 htmlDocument = epubReader.Document.DomDocument as IHTMLDocument2;
            IHTMLSelectionObject currentSelection = htmlDocument.selection;

            if (currentSelection != null)
            {
                IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;

                if (range != null)
                {
                    getText = range.text;
                }
            }
            else
            {
                System.Windows.MessageBox.Show("Please select text first !!");
            }
            //System.Diagnostics.Debug.WriteLine("in");
            return getText;
        }
        #endregion

        /// <summary>
        /// Add new bookmark
        /// </summary>
        /// <param name="tempBm">new bookmark</param>
        public override void AddBookmark(RoutedPropertyChangedEventArgs<object> e, string strSelectedItem, string strAddingItem, string strPageNumber)
        {
            string strBookmarkPageNumber = "";
            string strNodePath = "/Bookmark/";
            Stack<TreeViewItem> path = GetNodeParent(e.NewValue as UIElement);
            foreach (var treeViewItem in path)
            {
                strNodePath += "Title" + "/";
            }
            if (strNodePath.Length > 1)
            {
                //strNodePath += strSelectedItem.Substring(0, strSelectedItem.Length -1);
            }

            strNodePath = strNodePath.Substring(0, strNodePath.Length - 1);


            //strNodePath = "/Bookmark/Title/Title[contains(text(),'Errata')]";
            strNodePath += "[contains(text(),'" + strSelectedItem.Trim() + "')]";
            XmlNode node = xDoc.SelectSingleNode(strNodePath);
            if (node != null)
            {
                XmlElement childElement = xDoc.CreateElement("Title");
                childElement.InnerText = strAddingItem;
                childElement.SetAttribute("Page", strPageNumber + " ");
                childElement.SetAttribute("Action", "GoTo");
                node.ParentNode.AppendChild(childElement);
            }
            xDoc.Save(xmlFilePath);
        }

        /// <summary>
        /// Delete bookmark
        /// </summary>
        /// <param name="tempBm"></param>
        public override void DeleteBookmark(RoutedPropertyChangedEventArgs<object> e, string strSelectedItem)
        {
            string strBookmarkPageNumber = "";
            string strNodePath = "/Bookmark/Title/";
            Stack<TreeViewItem> path = GetNodeParent(e.NewValue as UIElement);
            foreach (var treeViewItem in path)
            {
                strNodePath += "Title" + "/";
            }
            if (strNodePath.Length > 1)
            {
                //strNodePath += strSelectedItem.Substring(0, strSelectedItem.Length -1);
            }

            strNodePath = strNodePath.Substring(0, strNodePath.Length - 1);


            //strNodePath = "/Bookmark/Title/Title[contains(text(),'Errata')]";
            strNodePath += "[contains(text(),'" + strSelectedItem.Trim() + "')]";
            XmlNode node = xDoc.SelectSingleNode(strNodePath);
            if (node != null)
            {
                node.ParentNode.RemoveChild(node);
            }
            xDoc.Save(xmlFilePath);
        }

        /// <summary>
        /// Update bookmark
        /// </summary>
        /// <param name="tempBm"></param>
        public override void UpdateBookmark(RoutedPropertyChangedEventArgs<object> e, string strSelectedItem, string strUpdateItem)
        {
            string strBookmarkPageNumber = "";
            string strNodePath = "/Bookmark/";
            Stack<TreeViewItem> path = GetNodeParent(e.NewValue as UIElement);
            foreach (var treeViewItem in path)
            {
                strNodePath += "Title" + "/";
            }
            if (strNodePath.Length > 1)
            {
                //strNodePath += strSelectedItem.Substring(0, strSelectedItem.Length -1);
            }

            strNodePath = strNodePath.Substring(0, strNodePath.Length - 1);


            //strNodePath = "/Bookmark/Title/Title[contains(text(),'Errata')]";
            strNodePath += "[contains(text(),'" + strSelectedItem.Trim() + "')]";
            XmlNode node = xDoc.SelectSingleNode(strNodePath);
            if (node != null)
            {
                node.InnerText = strUpdateItem;
            }
            xDoc.Save(xmlFilePath);
        }

        /// <summary>
        /// Search for content
        /// </summary>
        /// <param name="content">desired texts</param>
        [DllImport("user32.dll", SetLastError = true)]
        static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

        public const int VK_LCONTROL = 0xA2; //Left Control key code
        public const int F = 0x46; //A Control key code

        public override void SearchContent(string content)
        {
            this.epubReader.Focus();
            keybd_event(VK_LCONTROL, 0, 0, 0);
            keybd_event(F, 0, 0, 0);
            keybd_event(F, 0, 2, 0);
            keybd_event(VK_LCONTROL, 0, 2, 0);
        }

        /// <summary>
        /// Load Bookmark
        /// </summary>
        /// <returns></returns>
        public override void LoadBookmark(System.Windows.Controls.TreeView tvBookmark, string strXmlFilePath)
        {
            try
            {
                xDoc = new XmlDocument();
                xDoc.Load(strXmlFilePath);

                tvBookmark.Items.Clear();
                TreeViewItem nodeToAdd = new TreeViewItem();
                nodeToAdd.Header = xDoc.DocumentElement.Name;
                tvBookmark.Items.Add(nodeToAdd);
                TreeViewItem tNode = new TreeViewItem();
                tNode = (TreeViewItem)tvBookmark.Items[0];

                addTreeNode(xDoc.DocumentElement, tNode);
                foreach (TreeViewItem item in tvBookmark.Items)
                {
                    item.IsExpanded = true;
                }
            }
            catch (Exception)
            {
                //MessageBox.Show("a");
            }
        }

        /// <summary>
        /// Dispose Control
        /// </summary>
        public override void DisposeControl() { }

        public override void DisposeControl(bool disposing) { }

        public override string GetBookmarkPageNumber(RoutedPropertyChangedEventArgs<object> e, string strSelectedItem)
        {
            string strBookmarkPageNumber = "";
            string strNodePath = "/Bookmark/";
            Stack<TreeViewItem> path = GetNodeParent(e.NewValue as UIElement);
            foreach (var treeViewItem in path)
            {
                strNodePath += "Title" + "/";
            }

            strNodePath = strNodePath.Substring(0, strNodePath.Length - 1);

            strNodePath += "[contains(text(),'" + strSelectedItem.Trim() + "')]";

            XmlNode node = xDoc.SelectSingleNode(strNodePath);
            if (node != null)
            {
                XmlNode node2 = node.Attributes["Page"];
                if (node2 != null)
                {
                    string strPageNumber = node2.Value;
                    strPageNumber = strPageNumber.Substring(0, strPageNumber.IndexOf(" "));
                    if (strPageNumber != null)
                    {
                        strBookmarkPageNumber = strPageNumber;
                    }
                }

            }
            return strBookmarkPageNumber;
        }

        public static void ExportBookmarksToXml(string SourceEpubPath, string xmlOutputPath, string Password = "")
        {
            try
            {
                int intTotalPage = 0;
                Epub epub = new Epub(SourceEpubPath);
                string documentText = epub.GetContentAsHtml();
                intTotalPage = epub.epubPage;
                XmlDocument XD = new XmlDocument();
                XmlNode Root = XD.AppendChild(XD.CreateElement("Bookmark"));
                XmlElement childElement = XD.CreateElement("Title");
                childElement.InnerText = "First Page";
                childElement.SetAttribute("Page", "1 ");
                childElement.SetAttribute("Action", "GoTo");
                Root.AppendChild(childElement);
                childElement = XD.CreateElement("Title");
                childElement.InnerText = "Last Page";
                childElement.SetAttribute("Page", intTotalPage.ToString() + " ");
                childElement.SetAttribute("Action", "GoTo");
                Root.AppendChild(childElement);
                XmlDeclaration xmldecl;
                xmldecl = XD.CreateXmlDeclaration("1.0", null, null);
                xmldecl.Encoding = "ISO-8859-1";
                xmldecl.Standalone = "yes";
                XD.Save(xmlOutputPath);
            }
            catch (Exception)
            {
            }
        }

        private void addTreeNode(XmlNode xmlNode, TreeViewItem treeNode)
        {
            XmlNode xNode;
            TreeViewItem tNode;
            XmlNodeList xNodeList;
            string strInnerText;
            string strPageNumber;
            string strXPath;
            if (xmlNode.HasChildNodes) //The current node has children
            {
                xNodeList = xmlNode.ChildNodes;
                if (xNodeList.Count > 1)
                {
                    if (xmlNode.Name.Equals("Bookmark"))
                    {
                        for (int x = 0; x <= xNodeList.Count - 1; x++)
                        //Loop through the child nodes
                        {
                            xNode = xmlNode.ChildNodes[x];
                            strInnerText = xNode.InnerText;
                            if (strInnerText.Contains("\n"))
                            {
                                strInnerText = xNode.InnerText.Substring(0, xNode.InnerText.IndexOf("\n"));
                            }

                            treeNode.Items.Add(new TreeViewItem() { Header = strInnerText.Trim() });

                            tNode = treeNode.Items[x] as TreeViewItem;
                            addTreeNode(xNode, tNode);


                        }
                    }
                    else
                    {
                        for (int x = 1; x <= xNodeList.Count - 1; x++)
                        //Loop through the child nodes
                        {
                            xNode = xmlNode.ChildNodes[x];
                            strInnerText = xNode.InnerText;
                            if (strInnerText.Contains("\n"))
                            {
                                strInnerText = xNode.InnerText.Substring(0, xNode.InnerText.IndexOf("\n"));
                            }

                            treeNode.Items.Add(new TreeViewItem() { Header = strInnerText.Trim() });

                            tNode = treeNode.Items[x - 1] as TreeViewItem;
                            addTreeNode(xNode, tNode);


                        }
                    }
                }
                else
                {
                    xNode = xmlNode.ChildNodes[0];
                    treeNode.Header = xNode.InnerText.Trim();

                }

            }
            else
            {
                //No children, so add the outer xml (trimming off whitespace)         
                treeNode.Header = xmlNode.OuterXml.Trim();

            }


        }


        public static Stack<TreeViewItem> GetNodeParent(UIElement element)
        {

            Stack<TreeViewItem> tempNodePath = new Stack<TreeViewItem>();
            // Walk up the element tree to the nearest tree view item. 
            TreeViewItem container = element as TreeViewItem;


            while ((element != null))
            {

                element = VisualTreeHelper.GetParent(element) as UIElement;
                container = element as TreeViewItem;
                if (container != null)
                    tempNodePath.Push(container);
            }

            return tempNodePath;
        }

        public override Ebook GenerateEbookObj(string filePath)
        {
            Ebook myEbook = new Ebook();
            //File type
            FileInfo temp = new FileInfo(filePath);
            if (temp.Extension.Equals(".epub", StringComparison.InvariantCultureIgnoreCase))
            {
                myEbook.Type = ".epub";
            }
            //Create Ebook MetaData

            Epub getEpubBook = new Epub(filePath);
            string activePageCount = getEpubBook.GetContentAsHtml();
            myEbook.Title = Path.GetFileNameWithoutExtension(filePath);
            myEbook.Author = "Unknown";
            myEbook.Publisher = "Unknown";
            //if (getEpubBook.Title.Count > 0)
            //{
            //    myEbook.Title = getEpubBook.Title[0];
            //}
            if (getEpubBook.Creator.Count > 0)
            {
                myEbook.Author = getEpubBook.Creator[0];
            }
            if (getEpubBook.Publisher.Count > 0)
            {
                myEbook.Publisher = getEpubBook.Publisher[0];
            }
            if (getEpubBook.Description.Count > 0)
            {
                string getDescription = getEpubBook.Description[0];
                //Replace newline
                getDescription = Regex.Replace(getDescription, @"(<br/?>)", "\n", RegexOptions.Compiled);
                //Remove html tag
                getDescription = Regex.Replace(getDescription, @"(</?(\w+|\s*!--)[^>]*>)", " ", RegexOptions.Compiled);
                myEbook.Description = getDescription;
            }
            myEbook.Path = filePath;
            myEbook.ImportDate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            myEbook.Rating = 0;
            myEbook.CurrentPage = 0;
            myEbook.BookmarkPath = "AeReaderData\\Temp\\" + myEbook.Title + ".xml";
            myEbook.PageCount = getEpubBook.epubPage;

            return myEbook;
        }

        public override void GetPdfThumbnail(string sourcePdfFilePath, string destinationPngFilePath)
        {
            try { 
                Epub epub = new Epub(sourcePdfFilePath);

                string active = epub.GetContentAsHtml();
                active = epub.coverBase64;
                if (active != null)
                {
                    byte[] imageBytes = Convert.FromBase64String(active);
                    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
                    ms.Write(imageBytes, 0, imageBytes.Length);
                    System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
                    if (image.Width >= 300 && image.Height >= 400) { 
                        System.Drawing.Image newImage = image.GetThumbnailImage(300, 400, null, IntPtr.Zero);
                        newImage.Save(@destinationPngFilePath, System.Drawing.Imaging.ImageFormat.Png);
                    }
                    active = null;
                }
            }
            catch (Exception ex) {
                
            }
        }

        //---------------------End---------------------
    }
}
